package com.douguo.recipe;

import java.lang.ref.SoftReference;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import com.douguo.recipe.network.Constant;
import com.douguo.recipe.network.GetCachePhoto;
import com.douguo.recipe.network.GetEkSort;
import com.douguo.recipe.network.GetHotEkArticleList;
import com.douguo.recipe.network.GetPhoto;
import com.douguo.recipe.network.Util;
import com.douguo.recipe.object.EkArticle;
import com.douguo.recipe.object.EkSort;
import com.douguo.recipe.object.Sort;
import com.douguo.recipe.provider.DBHelper;
import com.douguo.recipe.view.NavigationView;

import android.app.Activity;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.DialogInterface.OnKeyListener;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.view.ViewGroup.LayoutParams;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.Button;
import android.widget.FrameLayout;
import android.widget.Gallery;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.SimpleAdapter;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.SimpleAdapter.ViewBinder;

public class EKMainActivity extends EKActivity {
	
	private static final String TAG = "EKMainActivity";
	
	private static final  int DIALOG_WAIT = 0;
	
	//---------------data-------------------
	private List<Map<String,Object>> mSorts;
	private List<Map<String,Object>> mHotArticles;
	private List<EkArticle> mArticles;
	private List<Sort> mAllSorts;
	private DouguoApplication mDouguoApplication;
	//----------------adapter---------------
	private SimpleAdapter mArticlesAdapter;
	private SimpleAdapter mSortsAdapter;
	
	//---------------ui---------------------
	private TextView mTvTitle;
	private TextView mTvContent;
	private Gallery mGallery;
	private NavigationView mNavigationView;
	private LinearLayout mGalleryPoints;
//	private LinearLayout mSortLayout;
//	private GridView mGridView;
	private Button mButtonReadArticle;
	
	private boolean isAutoDownloadThumb;
	private boolean isUseNetwork;
	
	private final static int MAX_RETRY_TIMES = 1;
	
	private Handler mHandler = new Handler() {
		public void handleMessage (Message msg) {
			switch(msg.what) {
			case Constant.MSG_HOT_EK_ARTICLE:
				mArticles = (List<EkArticle>) msg.obj;
				if(mArticles == null) {
					//error
					Toast.makeText(getApplicationContext(), R.string.getEKHotError, Toast.LENGTH_SHORT).show();
				}
				else {
					mDouguoApplication.getAppRuntime().put(Constant.GLOBAL_EK_ARTICLES, mArticles);
					for(EkArticle article : mArticles) {
						Map<String,Object> articleMap = new HashMap<String, Object>();
						Bitmap bitmap = BitmapFactory.decodeResource(
								getResources(), R.drawable.loading2);
						articleMap.put("articlePicPath", article.pic);
						articleMap.put("articleImg", article.title);
						articleMap.put("articleId", article.id);
						articleMap.put("recipeImg", bitmap);
						articleMap.put("useNetwork", Boolean.TRUE);
						articleMap.put("gettingImg", Boolean.FALSE);
						articleMap.put("retry", 0);
						mHotArticles.add(articleMap);
					}
					initGalleryPoints(mHotArticles.size());
					if(mArticles.size() > 0){
						fillCurrentArticle(mArticles.get(0).title,mArticles.get(0).summary);
						mArticlesAdapter.notifyDataSetChanged();
						enableGalleryPoint(0);
					}
				}
				try {
					dismissDialog(DIALOG_WAIT);
				}
				catch(Exception e) {
					//do nothing
				}
				break;
			case Constant.GET_PHOTO: 
				int pos = msg.arg1;
				SoftReference<Bitmap> refBitmap = (SoftReference<Bitmap>) msg.obj;
				Map<String, Object> hm = mHotArticles.get(pos);
				int retryTimes = (Integer) hm.get("retry");
				String thunmbPath = (String) hm.get("articlePicPath");
				if (refBitmap != null) {
					Bitmap bitmap = refBitmap.get();
					if (bitmap != null) {
						hm.put("articleImg", bitmap);
						mArticlesAdapter.notifyDataSetChanged();
					}

				} else if (refBitmap == null && retryTimes < MAX_RETRY_TIMES) {
					hm.put("retry", ++retryTimes);
					GetCachePhoto.getCachePhoto(pos, thunmbPath, mHandler);
				}

				break;
			case Constant.GET_EK_SORT:
				mAllSorts = (List<Sort>) msg.obj;
				if(mAllSorts != null) {
					for(Sort sort : mAllSorts) {
						Map<String,Object> sortMap = new HashMap<String, Object>();
						sortMap.put("ekSortName", sort.name);
						sortMap.put("ekSortId", sort.id);
						sortMap.put("ekSortPicId", sort.picId);
						mSorts.add(sortMap);
					}
					mSortsAdapter.notifyDataSetChanged();
//					updateGridWidth();
				}
				break;
			
			}
		}
	};
	
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.ek_main);
		mDouguoApplication = (DouguoApplication) getApplication();
		isAutoDownloadThumb = Util.isDownloadPhotoPreferences(this);
		isUseNetwork = Util.isUseNetworkPreferences(this);
		mNavigationView = new NavigationView(this, NavigationView.STATE_MAGAZINE);
		
		initData();
		initUI();
		if(isUseNetwork) {
			
			if(mDouguoApplication.getAppRuntime().get(Constant.GLOBAL_EK_ARTICLES) == null){
				showDialog(DIALOG_WAIT);
				GetHotEkArticleList.GetHotEkArticleList(mHandler);//after initUi
			}
			else {
				mHandler.sendMessage(mHandler.obtainMessage(Constant.MSG_HOT_EK_ARTICLE, mDouguoApplication.getAppRuntime().get(Constant.GLOBAL_EK_ARTICLES)));
			}
//			GetEkSort.getSort(getResources().openRawResource(R.raw.articlesort), mHandler);
		}
		else {
			//提示已关闭网络Toast.makeText(this, text, duration).show();
			Toast.makeText(this, R.string.networkClose, Toast.LENGTH_LONG).show();
			finish();
		}
	}
	
	public void initData() {
		mHotArticles = new ArrayList<Map<String,Object>>();
		mSorts = new ArrayList<Map<String,Object>>();
		mArticlesAdapter = new EKArticleListAdapter(this,mHotArticles,R.layout.home_galleryitem,new String[] {
				"articleImg", "articleId" }, new int[] {
				R.id.home_gallery_image });
		mArticlesAdapter.setViewBinder(new ViewBinder() {

			public boolean setViewValue(View view, Object data,
					String textRepresentation) {
				if (data instanceof Bitmap) {
					ImageView img = (ImageView) view;
					img.setImageBitmap((Bitmap) data);
					// img.setImageResource(R.drawable.gallery1);
				}
				return true;
			}
		});
		mSortsAdapter = new EKSortsAdapter(this,mSorts,R.layout.ek_sort_listitem,new String[] {
				"ekSortName", "ekSortId","ekSortPicId" }, new int[] {
				R.id.ek_sort_list_text });
		mSortsAdapter.setViewBinder(new ViewBinder() {

			public boolean setViewValue(View view, Object data,
					String textRepresentation) {
				if (data instanceof String) {
					TextView textview = (TextView) view;
					textview.setText((String) data);
					// img.setImageResource(R.drawable.gallery1);
				}
				return true;
			}
		});
	}
	
	private void initSort() {
		Sort sort = new EkSort();
//		sort.name = getString(R.string.)
	}
	
	public void initUI() {
		mTvTitle = (TextView) findViewById(R.id.ek_main_title);
		mTvContent = (TextView) findViewById(R.id.ek_main_content);
//		mGridView = (GridView) findViewById(R.id.ek_sort_grid);
//		mSortLayout = (LinearLayout) findViewById(R.id.ek_sort_linear);
		mGallery = (Gallery) findViewById(R.id.ek_main_gallery);
		mGallery.setAdapter(mArticlesAdapter);
		mGallery.setOnItemSelectedListener(new OnItemSelectedListener() {

			@Override
			public void onItemSelected(AdapterView<?> parent, View view,
					final int position, long id) {
				if(position < mArticles.size()) {
					fillCurrentArticle(mArticles.get(position).title, mArticles.get(position).summary);
					enableGalleryPoint(position);
					mButtonReadArticle.setOnClickListener(new OnClickListener() {
						
						@Override
						public void onClick(View v) {
							Intent intent = new Intent(getApplicationContext(), EKArticleActivity.class);
							intent.putExtra("article_url",Constant.URL_GET_EK_ARTICLE +  mArticles.get(position).id);
							startActivity(intent);
						}
					});
				}
				
			}
			
			@Override
			public void onNothingSelected(AdapterView<?> parent) {
				//do nothing
			}
		});
		mGallery.setOnItemClickListener(new OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView<?> adapterview, View arg1, int position,
					long arg3) {
				String title = mArticles.get(position).title;
				Intent intent = new Intent(getApplicationContext(),EKArticleActivity.class);
				intent.putExtra("article_url", Constant.URL_GET_EK_ARTICLE + mArticles.get(position).id);
				intent.putExtra("article_title", title);
				startActivity(intent);
			}
		});
		mGalleryPoints = (LinearLayout) findViewById(R.id.ek_main_gallery_points_layout);
//		mGridView.setAdapter(mSortsAdapter);
//		mGridView.setOnItemClickListener(new OnItemClickListener() {
//
//			@Override
//			public void onItemClick(AdapterView<?> parent, View view,
//					int position, long id) {
//				Intent intent = new Intent(getApplicationContext(),EKArticleListActivity.class);
//				Bundle bundle = new Bundle();
//				bundle.putString("sortId", mAllSorts.get(position).id);
//				bundle.putString("title", mAllSorts.get(position).name);
//				intent.putExtras(bundle);
//				startActivity(intent);
//				
//			}
//		});
		mButtonReadArticle = (Button) findViewById(R.id.ek_main_button_read_article);
		findViewById(R.id.imageButton_back).setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				finish();
				
			}
		});
		setTitle(getString(R.string.titleMeiShiEKan));
	}
	
	
	private void fillCurrentArticle(String title,String content) {
		mTvTitle.setText(title);
		mTvContent.setText(content);
	}
	
	private void initGalleryPoints(int number) {
		for(int i = 0; i < number; i++) {
			ImageView imgView = new ImageView(this);
			imgView.setImageResource(R.drawable.unselect_circle);
			imgView.setPadding(10, 0, 0, 0);
			mGalleryPoints.addView(imgView);
		}
		if(number > 0) {
			enableGalleryPoint(0);
		}
	}
	
	private void enableGalleryPoint(int position) {
		for(int i = 0 ;i < mGalleryPoints.getChildCount(); i++) {
			ImageView imgView = (ImageView) mGalleryPoints.getChildAt(i);
			if(position == i) {
				
				imgView.setImageResource(R.drawable.selected_circle);
			}
			else {
				imgView.setImageResource(R.drawable.unselect_circle);
			}
		}
	}
	
//	private void updateGridWidth(){
//		int width =  mSorts.size() * (70 + 4 * 2);
//		mSortLayout.setLayoutParams(new FrameLayout.LayoutParams(Util.dip2px(
//				this,width),
//				LayoutParams.WRAP_CONTENT));
//		mGridView.setNumColumns(mSorts.size());
////		mGrid.invalidate();
//	}
	
	@Override
	protected Dialog onCreateDialog(int id) {
		switch (id) {
		case DIALOG_WAIT:
			ProgressDialog progressDialog = new ProgressDialog(
					this);
			progressDialog.setMessage(this
					.getString(R.string.ekArticleDownloading));
			progressDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
			progressDialog.setOnKeyListener(new OnKeyListener() {

				public boolean onKey(DialogInterface dialog, int keyCode,
						KeyEvent event) {
					if (keyCode == KeyEvent.KEYCODE_BACK) {
						try {
							dismissDialog(DIALOG_WAIT);
						} catch (IllegalArgumentException e) {
							// do nothing
						}
						finish();
						return true;
					}
					return false;
				}
			});
			return progressDialog;
		}
		return null;
	}
	
	private class EKSortsAdapter extends SimpleAdapter {
		public EKSortsAdapter(Context context,
				List<? extends Map<String, ?>> data, int resource,
				String[] from, int[] to) {
			super(context, data, resource, from, to);
		}
		
		public View getView(int position, View convertView, ViewGroup parent) {
			View view = super.getView(position, convertView, parent);
			Map hm = (Map) getItem(position);
			int resid = getResources().getIdentifier((String) hm.get("ekSortPicId"), "drawable", "com.douguo.recipe");
			if(resid != 0) {
				view.setBackgroundResource(resid);
			}
			return view;
		}
	}
	
	private class EKArticleListAdapter extends SimpleAdapter {

		public EKArticleListAdapter(Context context,
				List<? extends Map<String, ?>> data, int resource,
				String[] from, int[] to) {
			super(context, data, resource, from, to);
		}

		public View getView(int position, View convertView, ViewGroup parent) {
			View view = super.getView(position, convertView, parent);
			Map map = (Map) getItem(position);
			if (isAutoDownloadThumb
					&& map.containsKey("useNetwork")
					&& map.get("useNetwork") == Boolean.TRUE
					&& (!map.containsKey("gettingImg") || map.get("gettingImg") == Boolean.FALSE)) {
				GetCachePhoto.getCachePhoto(position, (String) map.get("articlePicPath"), mHandler);
				map.put("gettingImg", Boolean.TRUE);
			}
			return view;
		}
	}
}
